package controllers

import org.slf4j.LoggerFactory

import play.api.data.Form
import play.api.data.Forms.text
import play.api.data.Forms.tuple
import play.api.i18n.Messages
import play.api.mvc.Action
import play.api.mvc.Controller

object Application extends Controller {

  def logger = LoggerFactory.getLogger("application")

  def index = Action { implicit request =>
    val username = request.session.get("username").getOrElse(null);
    if (username != null) {
      var newFlash = flash + ("username" -> username)
      Ok(views.html.main(lang, newFlash))
    } else {
      val loginForm = Form(
        tuple(
          "username" -> text,
          "password" -> text))
      Ok(views.html.login(lang, loginForm))
    }
  }

  def doLogin = Action { implicit request =>
    val loginForm = Form(
      tuple(
        "username" -> text,
        "password" -> text.verifying(
          Messages("login.validations.pwd"), t => t.equals("1234"))).verifying(
          Messages("login.validations.usr"), t => t._1.equals("1234")))
    //
    var form = loginForm.bindFromRequest
    if (form.hasErrors) {
      Ok(views.html.login(lang, form))
    } else {
      val username = form("username").value.getOrElse(null)
      var newFlash = flash + ("username" -> username)
      Ok(views.html.main(lang, newFlash)).withSession("username" -> username)
    }
  }

}